
package fr.mk25.audio{
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.errors.IOError;


    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;
    import flash.media.Sound;
    import flash.media.ID3Info;
    import flash.net.URLRequest;

    public class M3UPlaylist extends EventDispatcher{

        private var songs:Array;
        private var currentSong:Mp3FileHandler;
        private var currentSongIndex:int;
        private var previousSongIndex:int;
        private var sc:SoundChannel; 
        private var st:SoundTransform; 
    

        public function M3UPlaylist(mu3File:String=null){
            songs = new Array()
            st = new SoundTransform(0.5);

            if(mu3File != null){
                load(mu3File);       
            }

        }

        public function play():void{
            try{
                if(currentSong.getStatus() != Mp3FileHandler.PAUSED){
                    currentSong = new Mp3FileHandler(songs[currentSongIndex], st);
                    this.dispatchEvent(new PlaylistEvent( PlaylistEvent.PLAYING_NEW_TRACK  ));
                    currentSong.getMedia().addEventListener(Event.ID3, dispatchId3Received);
                }
            }catch(error:TypeError){
                currentSong = new Mp3FileHandler(songs[currentSongIndex], st);
                this.dispatchEvent(new PlaylistEvent( PlaylistEvent.PLAYING_NEW_TRACK  ));
                currentSong.getMedia().addEventListener(Event.ID3, dispatchId3Received);
            }
            sc = currentSong.play();
            sc.addEventListener(Event.SOUND_COMPLETE, onSongEnd);
        }

        public function pause():void{
            currentSong.pause();
        }

        public function setPlayMode(mode:int):void{

        }

        public function getNextSongIndex():int{
            return (currentSongIndex+1)%songs.length;
        }

        public function getPreviousSongIndex():int{
            return (currentSongIndex+songs.length-1)%songs.length;
        }

        public function playNext():void{
            currentSong.stop();
            currentSongIndex = this.getNextSongIndex();
            this.play();
        }
        public function playPrevious():void{
            currentSong.stop();
            currentSongIndex = this.getPreviousSongIndex();
            this.play();
        }
    

        public function getTrackID3():ID3Info{
            return currentSong.getID3();
        }    
    


        public function add(url:URLRequest):void{
            songs.push(url);
            if(songs.length == 1){
                currentSongIndex = 0;
            }
        }


        public function getProgress():Number{
            return currentSong.getProgress();
        }
        public function getProgressAsPercentage():Number{
            return currentSong.getProgressAsPercentage();
        }


        private function load(file:String):void{
            var fileUrlLoader:URLLoader = new URLLoader();
            fileUrlLoader.dataFormat = URLLoaderDataFormat.TEXT;

            fileUrlLoader.addEventListener(Event.COMPLETE, onMu3FileLoaded);
            //fileUrlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

            var request:URLRequest = new URLRequest(file);
            fileUrlLoader.load(request);
        }


        public function getVolume():Number{
            try{
                if( currentSong.getStatus() == Mp3FileHandler.PLAYING ){
                    return currentSong.getSoundTransform().volume * 100;
                }
                return 0;
            }catch(error:TypeError){
                trace("M3UPlaylist.getVolume : TypeError raised");
            }
            return 0;
        }

        public function setVolume(volume:Number):void{
            try{
                volume = (volume>=100)?100:volume;
                volume = (volume<=0)?0:volume;
                
                if(volume!=st.volume){
                    st.volume = volume / 100;
                    if( currentSong.getStatus() == Mp3FileHandler.PLAYING ){
                        currentSong.changeSoundTransform(st);
                    }
                }
            }catch(error:TypeError){
                trace("M3UPlaylist.setVolume : TypeError raised");
            }
        }


        // 
        // Event handler
        //
        private function onSongEnd(event:Event):void{
            this.playNext();
        }

        private function dispatchId3Received(event:Event):void{
            this.dispatchEvent(new PlaylistEvent( PlaylistEvent.ID3 ));
        }

        
        private function onMu3FileLoaded(event:Event):void{
            var fileContent:String = event.target.data as String;
            var lines:Array = fileContent.split("\n");
            var songPathes:Array = new Array();
            for(var i:int=0 ; i<lines.length; ++i){
                if( lines[i].indexOf("#")!=0  && (lines[i].indexOf(".mp3")!=-1 || lines[i].indexOf(".MP3")!=-1 )  ){
                    this.add( new URLRequest(lines[i]) );
                }
            }
            this.dispatchEvent(new PlaylistEvent( PlaylistEvent.LOADED ));
        }

    }

}
